import random
from playwright.async_api import async_playwright
from api.bit_api import *
from constant.country_constant import *
import asyncio
# 我想使用比特浏览器打开5个马来西亚，并访问指定网站。
# 分组BYBIT123-默认分组
group_id = "2c9bc058939b87300193a0aa99651fbc"  # 窗口ID从窗口配置woxian界面中复制，或者api创建后返回
#国家
country = "马来西亚"
#窗口数量
browser_id_sum = 1
#要打开的网址
open_url = "https://global.mytaurex.com/live_signup?brd=2&sidc=01059236-4428-44FE-AD02-AABAFD67868F"
# 本次代理地址
proxy_str = None


async def run():

    bit_browser_id_list = []
    for i in range(browser_id_sum):
        try:
            country_code = country_mapping[country].code
            print(f"{country} 的国家代码是 {country_code}")
        except KeyError:
            print(f"字典中没有找到 {country} 的国家代码")

        generate_random_available_foxyip(country_code)
        async with async_playwright() as playwright:
            try:
               bit_browser_id, page= await get_page(playwright)
            except Exception:
                pass
            bit_browser_id_list.append(bit_browser_id)
            try:
                await page.goto(
                    open_url, wait_until="commit")
            except Exception as e_xm_validate:
                pass
    while True:
        user_input = input("请输入内容（输入 '关闭' 进行下一步）：")
        if user_input == "关闭":
            print("关闭浏览器中....")
            # 这里添加下一步操作的代码
            for bit_browser_id in bit_browser_id_list:
                closeBrowser(bit_browser_id)
                deleteBrowser(bit_browser_id)
                print(f"已关闭{bit_browser_id}")
            break
        else:
            print("输入不是 '关闭'，请继续输入。")




# 创建一个在指定分组、指定国家、可以访问的浏览器
async def get_page(playwright):
        global proxy_str
        chromium = playwright.chromium
        host, port, account, password = parse_string(proxy_str)
        # 更新ip
        bit_browser_id = createBrowser(group_id, host, port, account, password)
        clear_browser(bit_browser_id)
        await asyncio.sleep(3)
        # proxies = {'http': '127.0.0.1:50001', 'https': '127.0.0.1:50001'}
        res = openBrowser(bit_browser_id)
        ws = res['data']['ws']
        print("ws address ==>>> ", ws)
        browser = await chromium.connect_over_cdp(ws)
        default_context = browser.contexts[0]
        # 关闭其他标签页
        existing_pages = default_context.pages
        for i, page in enumerate(existing_pages):
            if i > 0:  # 跳过第一个页面，关闭其他页面
                await page.close()
        page = await default_context.new_page()
        return bit_browser_id, page

# 根据国家编码获取随机可用的foxyip
def generate_random_available_foxyip(country_code):
    # 生成一个8位随机数字
    global proxy_str
    flag = True
    max_attempts = 10
    attempt = 0
    while flag and attempt < max_attempts:
        random_number = random.randint(10000000, 99999999)
        proxy_str = f"as.foxyip.com:7778:a123_custom_zone_{country_code}_sid_{random_number}_time_10:lei31400"
        if None is not open_url and check_proxy():
            flag = False
            print(f"可以使用{proxy_str}")
        else:
            print(f"不可以使用{proxy_str}")
        attempt += 1
    if flag:
        raise Exception("无法生成可用的代理字符串")
    return proxy_str


# 通过socket5测试代理IP可用性
def check_proxy():
    host, port, account, password = parse_string(proxy_str)
    proxy = {
        'http': f'http://{account}:{password}@{host}:{port}',
        'https': f'http://{account}:{password}@{host}:{port}'
    }

    headers = {
        'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.6261.95 Mobile Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Accept-Encoding': 'gzip, deflate, br'
    }

    try:
        # 发起请求，同时传入请求头
        requests.get(open_url, proxies=proxy, headers=headers, timeout=10)
        # 只要请求没有抛出异常，说明可以访问，返回 True
        return True
    except requests.RequestException:
        # 捕获所有请求异常，如超时、连接错误等
        return False

def parse_string(input_str):
    # 先按冒号分割
    parts = input_str.split(':')
    host = parts[0]
    port = parts[1]
    account = parts[2]
    password = parts[3]
    return host, port, account, password


if __name__ == "__main__":
    asyncio.run(run())